package com.main.UIOptions;

import com.gryffonx.Interfaces.generators.NameGeneratorsBinding;
import com.gryffonx.Interfaces.timeline.TimelineGeneratorBinding;
import com.gryffonx.Interfaces.dice.DiceRollerGUI;
import com.gryffonx.utils.StringUtils;
import com.gryffonx.utils.XMLFileFilter;
import com.main.printing.PrintingThread;
import com.main.AboutApplication;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

/**
 * @author Erik Stell
 * @version 1.0
 */
public class UIActionListeners {
    /**
     * @param thisPanel
     * @return
     */
    public static ActionListener saveAction(NameGeneratorsBinding thisPanel) {
        final NameGeneratorsBinding tmpPanel = thisPanel;
        ActionListener saveAction = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();

                fc.setCurrentDirectory(new File("./savedFiles"));
                fc.addChoosableFileFilter(new XMLFileFilter());
                fc.setAcceptAllFileFilterUsed(false);


                int returnVal = fc.showSaveDialog(null);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    //This is where a real application would save the file.

                    if (file.exists()) {
                        int response = JOptionPane.showConfirmDialog(null,
                                "Overwrite existing file?",
                                "Confirm Overwrite",
                                JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                    }


                    Document document = DocumentHelper.createDocument();
                    Element root = document.addElement("GeneratedNames");
                    for (int i = 0; i < tmpPanel.getTblSavedResults().getRowCount(); i++) {
                        String s = tmpPanel.getTblSavedResults().getValueAt(i, 0).toString();
                        root.addElement("name_item").addAttribute("name_id", Integer.toString(i)).addText(s);
                    }


                    try {
                        // lets write to a file
                        OutputFormat format = OutputFormat.createPrettyPrint();
                        XMLWriter writer = new XMLWriter(new FileWriter(file), format);
                        writer.write(document);
                        writer.close();

                    } catch (IOException ex) {
                        System.out.println(ex.getMessage());
                    }
                    //write the contents of a Swing component to a file object
                    //StringUtils.writeFile(file, tmpPanel.getTaResults().getText());
                }
            }
        };
        return saveAction;
    }

    public static ActionListener saveAction(TimelineGeneratorBinding thisPanel) {
        final TimelineGeneratorBinding tmpPanel = thisPanel;
        ActionListener saveAction = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();

                fc.setCurrentDirectory(new File("./savedFiles"));
                fc.addChoosableFileFilter(new XMLFileFilter());
                fc.setAcceptAllFileFilterUsed(false);


                int returnVal = fc.showSaveDialog(null);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    //This is where a real application would save the file.

                    if (file.exists()) {
                        int response = JOptionPane.showConfirmDialog(null,
                                "Overwrite existing file?",
                                "Confirm Overwrite",
                                JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                    }


                    Document document = DocumentHelper.createDocument();
                    Element root = document.addElement("Timeline");
                    for (int i = 0; i < tmpPanel.getTblTimelineTable().getRowCount(); i++) {
                        String dateS = tmpPanel.getTblTimelineTable().getValueAt(i, 0).toString();
                        String valueS = tmpPanel.getTblTimelineTable().getValueAt(i, 1).toString();

                        root.addElement("timeline_item").addAttribute("timeline_id", Integer.toString(i)).addAttribute("year", dateS).addText(valueS);
                    }


                    try {
                        // lets write to a file
                        OutputFormat format = OutputFormat.createPrettyPrint();
                        XMLWriter writer = new XMLWriter(new FileWriter(file), format);
                        writer.write(document);
                        writer.close();

                    } catch (IOException ex) {
                        System.out.println(ex.getMessage());
                    }

                    //write the contents of a Swing component to a file object
                    //StringUtils.writeFile(file, tmpPanel.getTaResults().getText());
                }
            }
        };
        return saveAction;
    }

    /**
     * @param thisPanel
     * @return
     */
    public static ActionListener openAction(NameGeneratorsBinding thisPanel) {
        final NameGeneratorsBinding tmpPanel = thisPanel;
        ActionListener openAction = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                fc.addChoosableFileFilter(new XMLFileFilter());
                fc.setAcceptAllFileFilterUsed(false);
                fc.setDialogTitle("Open File");

                // Choose only files, not directories
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

                // Start in current directory
                fc.setCurrentDirectory(new File("./savedFiles"));

                // Now open chooser
                int result = fc.showOpenDialog(null);
                if (result == JFileChooser.CANCEL_OPTION) {
                    //return true;
                } else if (result == JFileChooser.APPROVE_OPTION) {
                    //read the file
                    File file = fc.getSelectedFile();
                    String fileString = StringUtils.readFile(file);

                    if (fileString != null) {
                        SAXReader reader = new SAXReader();
                        Document xmlDoc = null;

                        DefaultTableModel testModel = tmpPanel.getSavedTableModel();
                        JTable tblResults = tmpPanel.getTblSavedResults();

                        //parse the document
                        try {
                            xmlDoc = reader.read(file);
                        } catch (DocumentException docE) {
                            docE.printStackTrace();
                        } catch (MalformedURLException malFormedE) {
                            malFormedE.printStackTrace();
                        }

                        Object[] trainingClassArray = xmlDoc.selectNodes("/GeneratedNames/name_item").toArray();
                        //iterate the name item results, appending the values to the saved items table
                        for (Object aTrainingClassArray : trainingClassArray) {
                            Node thisNode = (Node) aTrainingClassArray;
                            String val = thisNode.getStringValue();

                            Object[] myArry = {val};

                            testModel.addRow(myArry);
                            tblResults.setModel(testModel);

                        }

                        //write the read in file to a component, like a text area or JTable
                        //tmpPanel.getTaResults().setText(fileString);
                    }
                }
            }
        };

        return openAction;
    }

    public static ActionListener openAction(TimelineGeneratorBinding thisPanel) {
        final TimelineGeneratorBinding tmpPanel = thisPanel;
        ActionListener openAction = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                fc.addChoosableFileFilter(new XMLFileFilter());
                fc.setAcceptAllFileFilterUsed(false);
                fc.setDialogTitle("Open File");

                // Choose only files, not directories
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

                // Start in current directory
                fc.setCurrentDirectory(new File("./savedFiles"));

                // Now open chooser
                int result = fc.showOpenDialog(null);
                if (result == JFileChooser.CANCEL_OPTION) {
                    //return true;
                } else if (result == JFileChooser.APPROVE_OPTION) {
                    //read the file
                    File file = fc.getSelectedFile();
                    String fileString = StringUtils.readFile(file);

                    if (fileString != null) {
                        SAXReader reader = new SAXReader();
                        Document xmlDoc = null;

                        DefaultTableModel testModel = tmpPanel.getSavedTableModel();
                        JTable tblResults = tmpPanel.getTblTimelineTable();

                        //parse the document
                        try {
                            xmlDoc = reader.read(file);
                        } catch (DocumentException docE) {
                            docE.printStackTrace();
                        } catch (MalformedURLException malFormedE) {
                            malFormedE.printStackTrace();
                        }

                        Object[] trainingClassArray = xmlDoc.selectNodes("/Timeline/timeline_item").toArray();
                        //iterate the name item results, appending the values to the saved items table
                        for (Object aTrainingClassArray : trainingClassArray) {
                            Node thisNode = (Node) aTrainingClassArray;
                            System.out.println(thisNode);
                            String dateVal = thisNode.valueOf("@year");
                            String stringVal = thisNode.getStringValue();

                            Object[] myArry = {dateVal, stringVal};

                            testModel.addRow(myArry);
                            tblResults.setModel(testModel);

                        }

                        //write the read in file to a component, like a text area or JTable
                        //tmpPanel.getTaResults().setText(fileString);
                    }
                }
            }
        };

        return openAction;
    }

    /**
     * @param thisPanel
     * @return
     */
    public static ActionListener printAction(NameGeneratorsBinding thisPanel) {
        final NameGeneratorsBinding tmpPanel = thisPanel;
        ActionListener printAction = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                printCurrent(tmpPanel);
            }
        };
        return printAction;
    }

    public static ActionListener aboutAction(NameGeneratorsBinding thisPanel){
        final NameGeneratorsBinding tmpPanel = thisPanel;
        ActionListener aboutAction = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AboutApplication window = new AboutApplication();
                window.pack();
                int locationx = ((Toolkit.getDefaultToolkit().getScreenSize().width / 2));
                int windowWidth = (window.getWidth() / 2);
                int locationy = ((Toolkit.getDefaultToolkit().getScreenSize().height / 2));
                int windowHeight = (window.getHeight() / 2);

                window.setLocation(((Toolkit.getDefaultToolkit().getScreenSize().width / 2) -
                        (window.getWidth() / 2)),
                        ((Toolkit.getDefaultToolkit().getScreenSize().height / 2) -
                                (window.getHeight() / 2)));
                window.setVisible(true);
            }
        };

           return aboutAction;
    }


    private static synchronized void printCurrent(NameGeneratorsBinding tmpPanel) {
        ArrayList list = new ArrayList();
        list.add(tmpPanel.getTaResults().getText());
        if (list.size() > 0) {
            // do the actual printing in another thread
            new PrintingThread(list).start();
        }
    }

}